#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704

""" push commit msg to zentao """

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import time
import hashlib
import base64
# 以下是python2.7
from urllib import urlopen

ZENTAO_CODE="devOpsRobot"
ZENTAO_KEY="CCCC"
ZENTAO_BASE_URL="http://CCC:1111/zentao"

def zentaoComment(objecType, objectID, actionType, commentMsg, userId, extra=''):
  ##### invoke zentao
  # 按照zentao提供的扩展文档, 计算出本次调用时的token
  time1 = int(time.time())
  token = hashlib.md5((ZENTAO_CODE+ZENTAO_KEY+str(time1)).encode(encoding='UTF-8')).hexdigest()
  commentMsg = base64.b64encode(commentMsg).replace("+", "___").replace(" ", "____")
  visitUrl = '{}/api.php?m=action&f=comment2&objectType={}&objectID={}&actionType={}&comment={}&actor={}&extra={}&code={}&time={}&token={}'.format(ZENTAO_BASE_URL, objecType, objectID, actionType, commentMsg, userId, extra, ZENTAO_CODE, time1, token)
  # 发起调用
  response = urlopen(visitUrl)
  # 验证调用是否成功
  if(response.read().decode("UTF-8").isdigit()):
    return ("", 0)

  return (response.read().decode("UTF-8"), 1)

if __name__ == '__main__':
  #print(zentaoComment("story", "33617", "commented", "fulizhe---zzz", "luoqi", ""))
  import sys
  objectType = sys.argv[1]
  objectID = sys.argv[2]
  actionType = "commented"
  comment = sys.argv[3]
  actor = sys.argv[4]
  extra = ""
  zentaoComment(objectType, objectID, actionType, comment, actor, extra)